package servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 下载功能的Servlet，待下载的文件存储在WEB-INF/download目录下。
 * 运行本例时需要传递一个下载文件文件名的参数，比如：项目根目录/download.do?fileName=ferrari.jpg
 * @author Steven Suo
 *
 */
@WebServlet(
		urlPatterns = { "/download.do" }, 
		initParams = { 
				@WebInitParam(name = "downloadDir", value = "WEB-INF/download/")
		})
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String downloadDir;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	public void init(ServletConfig config){
		downloadDir = config.getServletContext().getRealPath(config.getInitParameter("downloadDir"));
	}
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String fileName = request.getParameter("fileName");
		File downloadFile = new File(downloadDir+fileName);
		//response.setContentType("application/pdf");;
		response.setHeader("content-disposition", "attachment;filename="+fileName);
		FileInputStream fis = new FileInputStream(downloadFile);
		byte[] buff = new byte[1024]; 
		ServletOutputStream out = response.getOutputStream();
		while (fis.read(buff) != -1) {
			out.write(buff);
		}
		out.close();
		fis.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
